package com.liuheng.manager.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.liuheng.manager.service.CategoryService;
import com.liuheng.spzx.model.entity.product.Category;
import org.springframework.beans.BeanUtils;

import java.util.List;


public class ExcelListener<CategoryExcelVo> implements ReadListener<CategoryExcelVo> {
    private static final int BATCH_COUNT = 100;
    private CategoryService categoryService;
    private List<Category> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public  ExcelListener(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @Override
    public void invoke(CategoryExcelVo t, AnalysisContext analysisContext) {
        Category category = new Category();
        BeanUtils.copyProperties(t,category);
        cachedDataList.add(category);
       if(cachedDataList.size()>=BATCH_COUNT){
           saveData();
           cachedDataList=ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
       }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
     saveData();
    }
    private void saveData(){
        categoryService.saveBatch((List<Category>)cachedDataList);
    }
}
